package com.tanhua.server.service;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.tanhua.autoconfig.template.AipFaceTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.UserLikeApi;
import com.tanhua.model.domain.User;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.model.vo.UserLikeVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.time.Duration;
import java.time.temporal.Temporal;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserInfoService {


    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private UserApi userApi;

    @DubboReference
    private UserLikeApi userLikeApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private TanhuaService tanhuaService;


    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }

    //更新用户头像
    public void updateHead(MultipartFile headPhoto, Long id) throws IOException {
        //1、将图片上传到阿里云oss
        String imageUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        //2、调用百度云判断是否包含人脸
        boolean detect = aipFaceTemplate.detect(imageUrl);
        //2.1 如果不包含人脸，抛出异常
        if(!detect) {
            throw new BusinessException(ErrorResult.faceError());
        }else{
            //2.2 包含人脸，调用API更新
            UserInfo userInfo = new UserInfo();
            userInfo.setId(id);
            userInfo.setAvatar(imageUrl);
            userInfoApi.update(userInfo);
        }
    }

    //根据id查寻
    public UserInfoVo findById(Long id) {
        UserInfo userInfo = userInfoApi.findById(id);

        UserInfoVo vo = new UserInfoVo();

        BeanUtils.copyProperties(userInfo,vo); //copy同名同类型的属性

        if(userInfo.getAge() != null) {
            vo.setAge(userInfo.getAge().toString());
        }

        return vo;
    }

    //更新
    public void update(UserInfo userInfo) {
        userInfoApi.update(userInfo);
    }

    /**
     * 互相喜欢、喜欢、粉丝、谁看过我 - 翻页列表
     */
    public PageResult findLikePages(Integer page, Integer pagesize, String nickname, String type) {
        //获取当前用户
        Long userId = UserHolder.getUserId();
        //查询"互相喜欢、喜欢、粉丝、谁看过我"的所有用户id
        List<Long> ids = userLikeApi.findIdsByIds(page,pagesize,userId,type);


        //不为空判断
        if (ids == null){
            throw new BusinessException(ErrorResult.nullError());
        }
        //根据ID查询用户详细信息
        UserInfo userInfo = new UserInfo();
        userInfo.setNickname(nickname);
        Map<Long, UserInfo> map = userInfoApi.findByIds(ids, userInfo);
        //构造VO
        List<UserLikeVo> vos = new ArrayList<>();
        for (Long id : ids) {
            UserLikeVo userLikeVo = new UserLikeVo();
            userLikeVo.setMatchRate(RandomUtil.randomInt(30,99));
        if (type.equals("1")){
            userLikeVo.setAlreadyLove(true);
        }else if(type.equals("2")){
            userLikeVo.setAlreadyLove(true);
        }else if(type.equals("3")) {
            userLikeVo.setAlreadyLove(false);
        }else if(type.equals("4")) {
            userLikeVo.setAlreadyLove(true);
        }
            UserInfo info = map.get(id);
            BeanUtils.copyProperties(info,userLikeVo);
            vos.add(userLikeVo);
        }
        return new PageResult(page,pagesize,0L,vos);
    }

    /**
     * 添加粉丝喜欢
     * @param fansId
     */
    public void saveLikeFans(Integer fansId) {
        Long fanId = fansId.longValue();
        tanhuaService.likeUser(fanId);
    }


    @Autowired
    private MessagesService messagesService;
    /**
     * 喜欢取消
     * @param disId
     */
    public void disLikeFans(Integer disId) {
        //
        Long userId = UserHolder.getUserId();
        Long disIdL = disId.longValue();
        userLikeApi.updateByIds(userId,disIdL);

        //2、操作redis，写入不喜欢的数据，删除喜欢的数据 (喜欢的集合，不喜欢的集合)
        redisTemplate.opsForSet().remove(Constants.USER_LIKE_KEY+UserHolder.getUserId(),disId.toString());
        redisTemplate.opsForSet().add(Constants.USER_NOT_LIKE_KEY+UserHolder.getUserId(),disId.toString());
    }

    //更新手机号,获取验证码
    public void sendMesg(String mobile) {
        //1.生成6位随机验证码
        //String code = RandomStringUtils.randomNumeric(6);
        //2.调用SmsTemplate,发送手机短信
        //smsTemplate.sendSms(phone,code);
        String code = "123456";
        //3.Redis缓存
        redisTemplate.opsForValue().set("CHECK_CODE1:"+mobile,code, Duration.ofMinutes(5));
    }

    //校验验证码
    public Map checkVerificationCode(String phone, String verificationCode) {
        //1、从redis中获取下发的验证码
        String redisCode = redisTemplate.opsForValue().get("CHECK_CODE1:" + phone);
        //2、对验证码进行校验（验证码是否存在，是否和输入的验证码一致）
        if(StringUtils.isEmpty(redisCode) || !redisCode.equals(verificationCode)) {
            //验证码无效
            throw new BusinessException(ErrorResult.loginError());
        }
        //3、删除redis中的验证码
        redisTemplate.delete("CHECK_CODE1:" + phone);
        Boolean verification = true;
        Map map = new HashMap();
        map.put("verification",verification);
        return map;
    }

    //保存手机
    public void savePhone(Long userId, String phone) {
        User user = new User();
        user.setId(userId);
        user.setMobile(phone);
        userApi.update(user);
    }

    //互相喜欢，喜欢，粉丝 - 统计
    public Map counts() {
        Long userId = UserHolder.getUserId();
        //调用api查询数据
        Map map = userLikeApi.counts(userId);
        return map;
    }
}
